const { database, host, username, password, dialect } = require("./config");
const { Sequelize, DataTypes } = require("sequelize")



//连接数据库
const sequelize = new Sequelize(database, username, password, {
    host: host,
    dialect: dialect
});

//测试连接数据库是否成功   
// (async () => {
//     try {
//         await sequelize.authenticate();
//         console.log('Connection has been established successfully.');
//     } catch (error) {
//         console.error('Unable to connect to the database:', error);
//     }
// })() 


//创建一个函数 包装模型的统一定义
function defineModel(name, attri) {
    let prop = {};

    prop.id = {
        type: DataTypes.BIGINT,
        primaryKey: true,
        autoIncrement: true
    };

    prop.remarks = {
        type: DataTypes.STRING(80),
        allowNull: true
    };

    prop.version = {
        type: DataTypes.BIGINT,
        allowNull: false
    };

    prop.createdAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    };

    prop.updatedAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    };

    //将外部定义的模型添加进来
    for (let r in attri) {
        let value = attri[r];
        prop[r] = value
    }


    //利用sequelize实例定义一个模型
    let obj = sequelize.define(name, prop, {
        tableName: name,
        timestamps: false,


        //创建一个勾子对象
        hooks: {
            //生命周期函数用来检测插入更新时,执行的方法(给更新与创建添加指定的时间戳值)
            beforeValidate: function (obj) {
                //获得时间戳
                let now = Date.now();
                //当第一次插入时
                if (obj.isNewRecord) {
                    obj.createdAt = now,
                        obj.updatedAt = now,
                        obj.version = 1
                } else {
                    obj.updatedAt = now,
                        obj.version += 1
                }


            }
        }

    })

    return obj;
}



module.exports ={
    sequelize,
    defineModel,
    DataTypes
}
